<template>
  <div class="virtual-gallery-container">
    <div class="gallery-header">
      <!-- <button class="back-button" @click="goBack">← 退出展览馆</button> -->
      <h1>虚拟书法展览馆</h1>
      <div class="spacer"></div>
    </div>

    <div ref="galleryContainer" class="gallery-model"></div>

    <div class="loading-indicator" v-if="loading">
      <div class="spinner"></div>
      <p>正在构建虚拟展览空间...</p>
    </div>

    <div class="gallery-controls">
      <div class="control-group">
        <button @mousedown="startMoveForward" @mouseup="stopMoveForward" @touchstart="startMoveForward" @touchend="stopMoveForward" title="前进">↑</button>
        <button @mousedown="startMoveBackward" @mouseup="stopMoveBackward" @touchstart="startMoveBackward" @touchend="stopMoveBackward" title="后退">↓</button>
        <button @mousedown="startMoveLeft" @mouseup="stopMoveLeft" @touchstart="startMoveLeft" @touchend="stopMoveLeft" title="左移">←</button>
        <button @mousedown="startMoveRight" @mouseup="stopMoveRight" @touchstart="startMoveRight" @touchend="stopMoveRight" title="右移">→</button>
      </div>

      <div class="control-group">
        <button @mousedown="startRotateLeft" @mouseup="stopRotateLeft" @touchstart="startRotateLeft" @touchend="stopRotateLeft" title="左转">↺</button>
        <button @mousedown="startRotateRight" @mouseup="stopRotateRight" @touchstart="startRotateRight" @touchend="stopRotateRight" title="右转">↻</button>
        <button @mousedown="startLookUp" @mouseup="stopLookUp" @touchstart="startLookUp" @touchend="stopLookUp" title="抬头">↾</button>
        <button @mousedown="startLookDown" @mouseup="stopLookDown" @touchstart="startLookDown" @touchend="stopLookDown" title="低头">⇂</button>
      </div>

      <div class="control-group">
        <button @mousedown="startZoomIn" @mouseup="stopZoomIn" @touchstart="startZoomIn" @touchend="stopZoomIn" title="放大">+</button>
        <button @mousedown="startZoomOut" @mouseup="stopZoomOut" @touchstart="startZoomOut" @touchend="stopZoomOut" title="缩小">-</button>
        <button @click="birdView" title="鸟瞰视角">👁</button>
        <button @click="resetView" title="重置视角">⌀</button>
      </div>

      <div class="control-group">
        <button @click="toggleAutoTour" :class="{ active: isAutoTouring }" title="自动导览">
          {{ isAutoTouring ? '停止' : '导览' }}
        </button>
      </div>
    </div>

    <!-- 操作提示 -->
    <div class="touch-hint" v-if="showHint">
      <p>💡 虚拟展览馆操作指南：</p>
      <p>• 鼠标拖动：环顾四周</p>
      <p>• 鼠标滚轮：前进/后退</p>
      <p>• WASD键：移动视角</p>
      <p>• 空格键：抬头/低头</p>
      <p>• +/-键：放大/缩小视角</p>
      <p>• 点击作品：查看详情</p>
      <button @click="hideHint">知道了</button>
    </div>

    <!-- 作品信息面板 -->
    <div class="artwork-info-panel" v-if="selectedArtwork">
      <div class="info-header">
        <h2>{{ selectedArtwork.title }}</h2>
        <button @click="closeInfoPanel" class="close-btn">×</button>
      </div>
      <div class="info-content">
        <p><strong>作者：</strong>{{ selectedArtwork.artist }}</p>
        <p><strong>朝代：</strong>{{ selectedArtwork.dynasty }}</p>
        <p><strong>书体：</strong>{{ selectedArtwork.style }}</p>
        <p><strong>简介：</strong>{{ selectedArtwork.description }}</p>
        <button @click="viewInDetail" class="detail-button">查看详情</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import * as THREE from 'three'
import { artworkApi } from '@/api'

// 路由和路由参数
const route = useRoute()
const router = useRouter()
const galleryContainer = ref(null)

// 3D相关变量
let scene, camera, renderer, gallery
let isAutoTouring = ref(false)
let animationId
let loading = ref(false)
let selectedArtwork = ref(null)

// 控制相关变量
let moveForward = false
let moveBackward = false
let moveLeft = false
let moveRight = false
let rotateLeft = false
let rotateRight = false
let lookUp = false
let lookDown = false
let zoomIn = false
let zoomOut = false

// 用户位置和方向
let userPosition = new THREE.Vector3(0, 1.6, 0) // 用户眼睛高度约1.6米
let userDirection = new THREE.Euler(0, 0, 0) // 用户视角方向
let userVelocity = new THREE.Vector3()

// 鼠标控制相关变量
let isMouseDown = false
let mouseStartX = 0
let mouseStartY = 0

// 操作提示
let showHint = ref(true)

// 作品数据
const artworks = ref([])

// 获取作品数据
const fetchArtworks = async () => {
  try {
    const response = await artworkApi.getArtworks()
    // 为每个作品添加位置和旋转信息
    artworks.value = response.data.map((artwork, index) => {
      // 计算位置，将作品均匀分布在展览馆中
      const positions = [
        new THREE.Vector3(-5, 1.5, -3),
        new THREE.Vector3(5, 1.5, -3),
        new THREE.Vector3(0, 1.5, -8),
        new THREE.Vector3(-8, 1.5, 2),
        new THREE.Vector3(8, 1.5, 2),
        new THREE.Vector3(0, 1.5, 5)
      ]
      
      const rotations = [
        new THREE.Euler(0, Math.PI / 6, 0),
        new THREE.Euler(0, -Math.PI / 6, 0),
        new THREE.Euler(0, 0, 0),
        new THREE.Euler(0, Math.PI / 4, 0),
        new THREE.Euler(0, -Math.PI / 4, 0),
        new THREE.Euler(0, Math.PI, 0)
      ]
      
      const positionIndex = index % positions.length
      
      return {
        ...artwork,
        position: positions[positionIndex] || new THREE.Vector3(0, 1.5, 0),
        rotation: rotations[positionIndex] || new THREE.Euler(0, 0, 0)
      }
    })
  } catch (error) {
    console.error('获取作品数据失败:', error)
    // 如果API调用失败，使用模拟数据
    useMockData()
  }
}

// 使用模拟数据（备用方案）
const useMockData = () => {
  artworks.value = [
    {
      id: 1,
      title: '兰亭序',
      artist: '王羲之',
      dynasty: '东晋',
      style: '行书',
      category: 'ancient',
      description: '被誉为"天下第一行书"，是王羲之在兰亭雅集时所作，书法飘逸秀美，气韵生动。',
      background: '东晋永和九年（353年），王羲之与谢安、孙绰等四十一位军政高官在山阴兰亭会聚，饮酒赋诗，王羲之为此诗集作序。',
      features: '笔法飘逸秀美，气韵生动，章法自然，体现了王羲之书法艺术的最高成就。此作品在3D建模中展现了笔画的立体感和墨色的层次变化。',
      image: 'https://img.dpm.org.cn/Uploads/Picture/2017/04/21/s58f9b14df3f14.jpg',
      position: new THREE.Vector3(-5, 1.5, -3),
      rotation: new THREE.Euler(0, Math.PI / 6, 0)
    },
    {
      id: 2,
      title: '祭侄文稿',
      artist: '颜真卿',
      dynasty: '唐代',
      style: '行书',
      category: 'ancient',
      description: '颜真卿为祭奠侄子颜季明所作，书法雄浑悲壮，被誉为"天下第二行书"。',
      background: '安史之乱时，颜真卿的侄子颜季明在抵抗叛军时被害，颜真卿悲愤交加写下此文。',
      features: '笔法雄浑，情感真挚，线条粗细变化丰富，体现了颜体行书的独特风格。3D建模突出了笔画的力度感和情感表达。',
      image: 'https://img.dpm.org.cn/Uploads/Picture/2017/04/21/s58f9b14df3f14.jpg',
      position: new THREE.Vector3(5, 1.5, -3),
      rotation: new THREE.Euler(0, -Math.PI / 6, 0)
    },
    {
      id: 3,
      title: '黄州寒食诗帖',
      artist: '苏轼',
      dynasty: '宋代',
      style: '行书',
      category: 'ancient',
      description: '苏轼被贬黄州时所作，书法自然流畅，情感真挚，体现了文人书法的独特韵味。',
      background: '苏轼被贬黄州第三年寒食节时所作，表达了对人生际遇的感慨。',
      features: '笔法自然，结构疏密有致，体现了文人书法的独特韵味。3D建模展现了字体的自然流动感。',
      image: 'https://images.unsplash.com/photo-1596580587800-9b4f9e9a0f8a?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=600&q=80',
      position: new THREE.Vector3(0, 1.5, -8),
      rotation: new THREE.Euler(0, 0, 0)
    },
    {
      id: 4,
      title: '自叙帖',
      artist: '怀素',
      dynasty: '唐代',
      style: '草书',
      category: 'ancient',
      description: '怀素的代表作之一，笔法狂放不羁，线条流畅如行云流水，展现了草书的极致之美。',
      background: '怀素在长安与文人雅士交往时所作，记录了自己学习草书的经历。',
      features: '笔法狂放，线条流畅如行云流水，展现了草书的极致之美。3D建模突出了草书的动感和韵律。',
      image: 'https://img.dpm.org.cn/Uploads/Picture/dc/19319[1024].jpg',
      position: new THREE.Vector3(-8, 1.5, 2),
      rotation: new THREE.Euler(0, Math.PI / 4, 0)
    },
    {
      id: 5,
      title: '急就章',
      artist: '宋克',
      dynasty: '明代',
      style: '章草',
      category: 'ancient',
      description: '明代书法家宋克的章草代表作，笔法古朴，结构严谨，体现了章草的独特韵味。',
      background: '明代书法家宋克的章草代表作，体现了章草的独特韵味。',
      features: '笔法古朴，结构严谨，体现了章草的独特韵味。3D建模还原了古朴的笔法特征。',
      image: 'https://img.dpm.org.cn/Uploads/Picture/dc/19319[1024].jpg',
      position: new THREE.Vector3(8, 1.5, 2),
      rotation: new THREE.Euler(0, -Math.PI / 4, 0)
    },
    {
      id: 6,
      title: '毛泽东诗词',
      artist: '毛泽东',
      dynasty: '现代',
      style: '草书',
      category: 'modern',
      description: '毛泽东的书法作品，气势磅礴，笔力雄健，体现了革命家的豪迈气概。',
      background: '毛泽东的书法作品，体现了革命家的豪迈气概。',
      features: '气势磅礴，笔力雄健，体现了革命家的豪迈气概。3D建模展现了豪迈的气势。',
      image: 'https://img.dpm.org.cn/Uploads/Picture/dc/19319[1024].jpg',
      position: new THREE.Vector3(0, 1.5, 5),
      rotation: new THREE.Euler(0, Math.PI, 0)
    }
  ]
}

// 返回上一页
const goBack = () => {
  router.push('/exhibition')
}

// 隐藏提示
const hideHint = () => {
  showHint.value = false
}

// 关闭信息面板
const closeInfoPanel = () => {
  selectedArtwork.value = null
}

// 查看详情
const viewInDetail = () => {
  if (selectedArtwork.value) {
    router.push(`/exhibition/${selectedArtwork.value.id}`)
  }
}

// 初始化展览馆
const initGallery = () => {
  if (!galleryContainer.value) return

  // 创建场景
  scene = new THREE.Scene()
  scene.background = new THREE.Color(0x1a1a2e)
  scene.fog = new THREE.Fog(0x1a1a2e, 10, 25)

  // 创建相机
  camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  camera.position.copy(userPosition)
  
  // 创建渲染器
  renderer = new THREE.WebGLRenderer({ antialias: true })
  renderer.setSize(window.innerWidth, window.innerHeight)
  renderer.setPixelRatio(window.devicePixelRatio)
  galleryContainer.value.innerHTML = ''
  galleryContainer.value.appendChild(renderer.domElement)

  // 添加光源
  const ambientLight = new THREE.AmbientLight(0xffffff, 0.6)
  scene.add(ambientLight)

  const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8)
  directionalLight.position.set(5, 10, 7)
  directionalLight.castShadow = true
  scene.add(directionalLight)

  const hemisphereLight = new THREE.HemisphereLight(0xffffbb, 0x080820, 0.5)
  scene.add(hemisphereLight)

  // 创建展览馆环境
  createGalleryEnvironment()

  // 创建作品展示
  createArtworkDisplays()

  // 开始渲染循环
  renderer.setAnimationLoop(animate)

  // 窗口大小调整
  window.addEventListener('resize', onWindowResize)

  // 添加事件监听器
  addEventListeners()
}

// 创建展览馆环境
const createGalleryEnvironment = () => {
  // 创建地面
  const floorGeometry = new THREE.PlaneGeometry(30, 30)
  const floorMaterial = new THREE.MeshStandardMaterial({ 
    color: 0x2c3e50,
    roughness: 0.8,
    metalness: 0.2
  })
  const floor = new THREE.Mesh(floorGeometry, floorMaterial)
  floor.rotation.x = -Math.PI / 2
  floor.receiveShadow = true
  scene.add(floor)

  // 创建墙壁
  const wallMaterial = new THREE.MeshStandardMaterial({ 
    color: 0x34495e,
    roughness: 0.7,
    metalness: 0.1
  })

  // 后墙
  const backWall = new THREE.Mesh(
    new THREE.BoxGeometry(30, 10, 0.5),
    wallMaterial
  )
  backWall.position.set(0, 5, -15)
  backWall.receiveShadow = true
  scene.add(backWall)

  // 左墙
  const leftWall = new THREE.Mesh(
    new THREE.BoxGeometry(0.5, 10, 30),
    wallMaterial
  )
  leftWall.position.set(-15, 5, 0)
  leftWall.receiveShadow = true
  scene.add(leftWall)

  // 右墙
  const rightWall = new THREE.Mesh(
    new THREE.BoxGeometry(0.5, 10, 30),
    wallMaterial
  )
  rightWall.position.set(15, 5, 0)
  rightWall.receiveShadow = true
  scene.add(rightWall)

  // 添加装饰性柱子
  for (let i = -2; i <= 2; i++) {
    if (i === 0) continue // 跳过中心位置
    
    const pillarGeometry = new THREE.CylinderGeometry(0.3, 0.3, 10, 16)
    const pillarMaterial = new THREE.MeshStandardMaterial({ 
      color: 0x7f8c8d,
      roughness: 0.6,
      metalness: 0.3
    })
    
    const pillar = new THREE.Mesh(pillarGeometry, pillarMaterial)
    pillar.position.set(i * 6, 5, -14.5)
    pillar.castShadow = true
    pillar.receiveShadow = true
    scene.add(pillar)
  }

  // 添加天花板
  const ceilingGeometry = new THREE.BoxGeometry(30, 0.5, 30)
  const ceilingMaterial = new THREE.MeshStandardMaterial({ 
    color: 0x2c3e50,
    roughness: 0.8,
    metalness: 0.1
  })
  const ceiling = new THREE.Mesh(ceilingGeometry, ceilingMaterial)
  ceiling.position.set(0, 10, 0)
  ceiling.receiveShadow = true
  scene.add(ceiling)

  // 添加装饰性吊灯
  for (let i = -1; i <= 1; i++) {
    for (let j = -1; j <= 1; j++) {
      const lightGeometry = new THREE.SphereGeometry(0.3, 16, 16)
      const lightMaterial = new THREE.MeshBasicMaterial({ color: 0xf39c12 })
      const light = new THREE.Mesh(lightGeometry, lightMaterial)
      light.position.set(i * 8, 9, j * 8)
      scene.add(light)
      
      // 添加光源
      const pointLight = new THREE.PointLight(0xf39c12, 1, 10)
      pointLight.position.set(i * 8, 8.5, j * 8)
      scene.add(pointLight)
    }
  }
}

// 创建作品展示
const createArtworkDisplays = () => {
  const textureLoader = new THREE.TextureLoader()
  
  artworks.value.forEach((artwork) => {
    // 创建展示台
    const displayGroup = new THREE.Group()
    
    // 展示台底座
    const baseGeometry = new THREE.CylinderGeometry(1.5, 1.5, 0.3, 32)
    const baseMaterial = new THREE.MeshStandardMaterial({ 
      color: 0x7f8c8d,
      roughness: 0.7,
      metalness: 0.3
    })
    const base = new THREE.Mesh(baseGeometry, baseMaterial)
    base.position.y = 0.15
    base.castShadow = true
    base.receiveShadow = true
    displayGroup.add(base)
    
    // 展示板
    const boardGeometry = new THREE.BoxGeometry(2.5, 3, 0.1)
    const boardMaterial = new THREE.MeshStandardMaterial({
      color: 0xf5f5dc, // 米黄色，类似宣纸
      roughness: 0.8,
      metalness: 0.1
    })
    const board = new THREE.Mesh(boardGeometry, boardMaterial)
    board.position.y = 2
    board.castShadow = true
    displayGroup.add(board)
    
    // 加载作品图片作为纹理
    textureLoader.load(artwork.image, (texture) => {
      const artworkMaterial = new THREE.MeshStandardMaterial({
        map: texture,
        roughness: 0.9,
        metalness: 0.0
      })
      
      // 创建作品展示面
      const artworkGeometry = new THREE.PlaneGeometry(2.3, 2.8)
      const artworkMesh = new THREE.Mesh(artworkGeometry, artworkMaterial)
      artworkMesh.position.set(0, 2, 0.06)
      displayGroup.add(artworkMesh)
    }, undefined, (err) => {
      console.error('加载作品图片失败:', err)
    })
    
    // 设置展示台位置和旋转
    displayGroup.position.copy(artwork.position)
    displayGroup.rotation.copy(artwork.rotation)
    
    // 添加到场景
    scene.add(displayGroup)
    
    // 保存引用以便交互
    artwork.displayObject = displayGroup
  })
}

// 添加点击检测功能
const onMouseClick = (event) => {
  // 创建射线投射器
  const raycaster = new THREE.Raycaster()
  const mouse = new THREE.Vector2()
  
  // 计算鼠标位置标准化设备坐标 (-1 到 +1)
  const rect = renderer.domElement.getBoundingClientRect()
  mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1
  mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1
  
  // 通过相机和鼠标位置更新射线
  raycaster.setFromCamera(mouse, camera)
  
  // 计算与场景中对象的交点
  const intersects = raycaster.intersectObjects(scene.children, true)
  
  // 检查是否点击了作品
  for (let i = 0; i < intersects.length; i++) {
    const intersect = intersects[i]
    // 查找被点击的对象是否属于某个作品展示组
    let object = intersect.object
    while (object) {
      // 检查对象是否是作品展示组的一部分
      for (const artwork of artworks.value) {
        if (artwork.displayObject && artwork.displayObject.uuid === object.parent.uuid) {
        console.log('点击对象121:', object)
          // 设置选中的作品
          selectedArtwork.value = artwork
          return
        }
      }
      object = object.parent
    }
  }
}

// 渲染动画循环
const animate = () => {
  // 更新用户位置
  updateMovement()
  
  // 更新相机位置和方向
  camera.position.copy(userPosition)
  camera.rotation.copy(userDirection)
  
  // 自动导览逻辑
  if (isAutoTouring.value) {
    // 简单的自动导览逻辑
    userDirection.y += 0.005
  }
  
  renderer.render(scene, camera)
}

// 更新移动
const updateMovement = () => {
  const speed = 0.1
  const rotateSpeed = 0.03
  const zoomSpeed = 0.1
  
  // 旋转
  if (rotateLeft) userDirection.y += rotateSpeed
  if (rotateRight) userDirection.y -= rotateSpeed
  if (lookUp) userDirection.x += rotateSpeed
  if (lookDown) userDirection.x -= rotateSpeed
  
  // 限制上下视角
  userDirection.x = Math.max(-Math.PI/2, Math.min(Math.PI/2, userDirection.x))
  
  // 移动
  const direction = new THREE.Vector3()
  if (moveForward) direction.z -= 1
  if (moveBackward) direction.z += 1
  if (moveLeft) direction.x -= 1
  if (moveRight) direction.x += 1
  
  // 根据当前视角方向调整移动方向
  if (direction.length() > 0) {
    direction.normalize()
    direction.applyEuler(new THREE.Euler(0, userDirection.y, 0))
    userPosition.add(direction.multiplyScalar(speed))
  }
  
  // 缩放（通过前后移动实现视觉缩放效果）
  if (zoomIn) {
    const zoomDirection = new THREE.Vector3(0, 0, -1)
    zoomDirection.applyEuler(new THREE.Euler(0, userDirection.y, 0))
    userPosition.add(zoomDirection.multiplyScalar(zoomSpeed))
  }
  
  if (zoomOut) {
    const zoomDirection = new THREE.Vector3(0, 0, 1)
    zoomDirection.applyEuler(new THREE.Euler(0, userDirection.y, 0))
    userPosition.add(zoomDirection.multiplyScalar(zoomSpeed))
  }
}

// 控制函数
const startMoveForward = () => { moveForward = true }
const stopMoveForward = () => { moveForward = false }

const startMoveBackward = () => { moveBackward = true }
const stopMoveBackward = () => { moveBackward = false }

const startMoveLeft = () => { moveLeft = true }
const stopMoveLeft = () => { moveLeft = false }

const startMoveRight = () => { moveRight = true }
const stopMoveRight = () => { moveRight = false }

const startRotateLeft = () => { rotateLeft = true }
const stopRotateLeft = () => { rotateLeft = false }

const startRotateRight = () => { rotateRight = true }
const stopRotateRight = () => { rotateRight = false }

const startLookUp = () => { lookUp = true }
const stopLookUp = () => { lookUp = false }

const startLookDown = () => { lookDown = true }
const stopLookDown = () => { lookDown = false }

const startZoomIn = () => { zoomIn = true }
const stopZoomIn = () => { zoomIn = false }

const startZoomOut = () => { zoomOut = true }
const stopZoomOut = () => { zoomOut = false }

const birdView = () => {
  // 切换到鸟瞰视角
  userPosition.set(0, 8, 0)
  userDirection.set(-Math.PI/2, 0, 0)
}

const resetView = () => {
  // 重置视角
  userPosition.set(0, 1.6, 0)
  userDirection.set(0, 0, 0)
}

const toggleAutoTour = () => {
  isAutoTouring.value = !isAutoTouring.value
}

// 窗口大小调整
const onWindowResize = () => {
  if (!camera || !renderer) return

  camera.aspect = window.innerWidth / window.innerHeight
  camera.updateProjectionMatrix()
  renderer.setSize(window.innerWidth, window.innerHeight)
}

// 添加事件监听器
const addEventListeners = () => {
  // 键盘事件
  document.addEventListener('keydown', onKeyDown)
  document.addEventListener('keyup', onKeyUp)
  
  // 鼠标事件
  renderer.domElement.addEventListener('mousedown', onMouseDown)
  renderer.domElement.addEventListener('mouseup', onMouseUp)
  renderer.domElement.addEventListener('mousemove', onMouseMove)
  renderer.domElement.addEventListener('wheel', onMouseWheel)
  renderer.domElement.addEventListener('click', onMouseClick)
  
  // 触屏事件
  renderer.domElement.addEventListener('touchstart', onTouchStart)
  renderer.domElement.addEventListener('touchend', onTouchEnd)
  renderer.domElement.addEventListener('touchmove', onTouchMove)
}

// 键盘按下事件
const onKeyDown = (event) => {
  switch (event.code) {
    case 'KeyW': moveForward = true; break
    case 'KeyS': moveBackward = true; break
    case 'KeyA': moveLeft = true; break
    case 'KeyD': moveRight = true; break
    case 'ArrowLeft': rotateLeft = true; break
    case 'ArrowRight': rotateRight = true; break
    case 'Space': lookUp = true; break
    case 'Equal': 
    case 'NumpadAdd': zoomIn = true; break
    case 'Minus': 
    case 'NumpadSubtract': zoomOut = true; break
  }
}

// 键盘释放事件
const onKeyUp = (event) => {
  switch (event.code) {
    case 'KeyW': moveForward = false; break
    case 'KeyS': moveBackward = false; break
    case 'KeyA': moveLeft = false; break
    case 'KeyD': moveRight = false; break
    case 'ArrowLeft': rotateLeft = false; break
    case 'ArrowRight': rotateRight = false; break
    case 'Space': lookUp = false; lookDown = false; break
    case 'Equal': 
    case 'NumpadAdd': zoomIn = false; break
    case 'Minus': 
    case 'NumpadSubtract': zoomOut = false; break
  }
}

// 鼠标按下事件
const onMouseDown = (event) => {
  isMouseDown = true
  mouseStartX = event.clientX
  mouseStartY = event.clientY
}

// 鼠标释放事件
const onMouseUp = () => {
  isMouseDown = false
}

// 鼠标移动事件
const onMouseMove = (event) => {
  if (isMouseDown) {
    const deltaX = event.clientX - mouseStartX
    const deltaY = event.clientY - mouseStartY
    
    userDirection.y -= deltaX * 0.01
    userDirection.x -= deltaY * 0.01
    
    // 限制上下视角
    userDirection.x = Math.max(-Math.PI/2, Math.min(Math.PI/2, userDirection.x))
    
    mouseStartX = event.clientX
    mouseStartY = event.clientY
  }
}

// 鼠标滚轮事件
const onMouseWheel = (event) => {
  const speed = 0.1
  const direction = new THREE.Vector3(0, 0, Math.sign(event.deltaY))
  direction.applyEuler(new THREE.Euler(0, userDirection.y, 0))
  userPosition.add(direction.multiplyScalar(-speed))
}

// 触屏开始事件
const onTouchStart = (event) => {
  if (event.touches.length === 1) {
    // 单指触摸用于旋转视角
    mouseStartX = event.touches[0].clientX
    mouseStartY = event.touches[0].clientY
  }
}

// 触屏结束事件
const onTouchEnd = () => {
  // 无特殊处理
}

// 触屏移动事件
const onTouchMove = (event) => {
  if (event.touches.length === 1) {
    const deltaX = event.touches[0].clientX - mouseStartX
    const deltaY = event.touches[0].clientY - mouseStartY
    
    userDirection.y -= deltaX * 0.01
    userDirection.x -= deltaY * 0.01
    
    // 限制上下视角
    userDirection.x = Math.max(-Math.PI/2, Math.min(Math.PI/2, userDirection.x))
    
    mouseStartX = event.touches[0].clientX
    mouseStartY = event.touches[0].clientY
  }
}

// 组件挂载时初始化
onMounted(() => {
  fetchArtworks().then(() => {
    initGallery()
  })
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', onWindowResize)
  document.removeEventListener('keydown', onKeyDown)
  document.removeEventListener('keyup', onKeyUp)
  
  if (animationId) {
    cancelAnimationFrame(animationId)
  }
  if (renderer) {
    renderer.dispose()
  }
})
</script>

<style scoped>
.virtual-gallery-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: #1a1a2e;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.gallery-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  z-index: 10;
}

.gallery-header h1 {
  margin: 0;
  font-size: 1.5rem;
}

.back-button {
  background-color: #667eea;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
}

.back-button:hover {
  background-color: #5a6fd8;
}

.spacer {
  width: 60px;
}

.gallery-model {
  flex: 1;
  width: 100%;
}

.loading-indicator {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: white;
  z-index: 5;
}

.spinner {
  border: 4px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top: 4px solid #fff;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
  margin: 0 auto 1rem;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.gallery-controls {
  position: absolute;
  bottom: 2rem;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 1rem;
  z-index: 10;
}

.control-group {
  display: flex;
  gap: 0.5rem;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 0.5rem;
  border-radius: 8px;
}

.control-group button {
  width: 40px;
  height: 40px;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  display: flex;
  align-items: center;
  justify-content: center;
}

.control-group button:hover {
  background-color: #667eea;
}

.control-group button.active {
  background-color: #667eea;
}

.touch-hint {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 2rem;
  border-radius: 10px;
  text-align: center;
  z-index: 20;
  max-width: 90%;
  width: 500px;
}

.touch-hint p {
  margin: 0.5rem 0;
  text-align: left;
}

.touch-hint button {
  background-color: #667eea;
  color: white;
  border: none;
  padding: 0.8rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  margin-top: 1rem;
}

.touch-hint button:hover {
  background-color: #5a6fd8;
}

.artwork-info-panel {
  position: absolute;
  top: 0;
  right: 0;
  width: 350px;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.95);
  box-shadow: -5px 0 15px rgba(0, 0, 0, 0.3);
  z-index: 15;
  display: flex;
  flex-direction: column;
}

.info-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem;
  background-color: #34495e;
  color: white;
}

.info-header h2 {
  margin: 0;
  font-size: 1.3rem;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
}

.info-content {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
}

.info-content p {
  margin: 0.8rem 0;
  line-height: 1.5;
}

.detail-button {
  background-color: #667eea;
  color: white;
  border: none;
  padding: 0.8rem 1.5rem;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  margin-top: 1rem;
  width: 100%;
}

.detail-button:hover {
  background-color: #5a6fd8;
}

@media (max-width: 768px) {
  .gallery-header {
    padding: 0.5rem 1rem;
  }

  .gallery-header h1 {
    font-size: 1.2rem;
  }

  .touch-hint {
    width: 90%;
    padding: 1.5rem;
  }

  .gallery-controls {
    bottom: 1rem;
    flex-wrap: wrap;
    justify-content: center;
    width: 90%;
    left: 5%;
    transform: none;
  }

  .artwork-info-panel {
    width: 100%;
  }
}
</style>